package com.androidservice.android.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.ServerSocket;
import java.net.URL;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.RequestMap;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.beans.factory.annotation.Autowired;

import com.androidservice.bean.OpenArea;
//import com.androidservice.bean.OpenArea;
import com.androidservice.dao.OpenAreaDao;
import com.androidservice.util.MiscUtils;
import com.opensymphony.xwork2.ActionSupport;

public class FindPackageAction extends ActionSupport implements SessionAware,ServletResponseAware, RequestAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private HttpServletResponse response;
	
	@SuppressWarnings("rawtypes")
	private SessionMap session;

	private RequestMap request;
			
	private String place;
	
	@Autowired
	private OpenAreaDao openareaDao;
	
	
	public String getPlace() {
		return place;
	}


	public void setPlace(String place) {
		this.place = place;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void setRequest(Map map) {
		this.request = (RequestMap) map;
	}
	
	public RequestMap getRequest() {
		return request;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	public HttpServletResponse getResponse() {
		return response;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void setSession(Map map) {
		this.session = (SessionMap) map;
	}
	
	@SuppressWarnings("rawtypes")
	public SessionMap getSession() {
		return session;
	}
	
	public static String ConvertToString(InputStream inputStream){  
        InputStreamReader inputStreamReader = null;
		try {
			inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}  
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
        StringBuilder result = new StringBuilder();  
        String line = null;
        try {  
            while((line = bufferedReader.readLine()) != null){  
                result.append(line + "\n");  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            try{  
                inputStreamReader.close();  
                inputStream.close();  
                bufferedReader.close();  
            }catch(IOException e){  
                e.printStackTrace();  
            }  
        }  
        return result.toString();  
    } 
	
	public String sendUrl(){
		String url = "";
		String http = "";
		HttpServletRequest httpRequest = ServletActionContext.getRequest();
		http = httpRequest.getScheme() + "://" + httpRequest.getServerName() + ":" + httpRequest.getServerPort();
		
		OpenArea openarea = openareaDao.findOpenAreaByAbridge(place);
		url = http + "/" + openarea.getPackagename();
//		if(null != place){
//			if(place.contains("nj")){
//				url = http + "/mobile";
//			}
//			if(place.contains("cz")){
//				url = http + "/cz";
//			}
//			if(place.contains("tz")){
//				url = http + "/tz";
//			}
//			if(place.contains("nt")){
//				url = http + "/nt";
//			}
//			if(place.contains("ha")){
//				url = http + "/ha";
//			}
//		}else{
//			return null;
//		}
		url = url + httpRequest.getServletPath();
		url = url + "_forward";
		if (httpRequest.getQueryString() != null || !"".equals(httpRequest.getQueryString())) {
			url = url + "?" + httpRequest.getQueryString();
		}
		
		try {
			response.sendRedirect(url);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String findPackage(){
		String url = "";
		String http = "";
		HttpServletRequest httpRequest = ServletActionContext.getRequest();
//		http = httpRequest.getScheme() + "://" + httpRequest.getServerName() + ":" + httpRequest.getServerPort();
		http = httpRequest.getScheme() + "://" + httpRequest.getServerName() + ":" + "8080";
		
		OpenArea openarea = openareaDao.findOpenAreaByAbridge(place);
		url = http + "/" + openarea.getPackagename();
//		if(null != place){
//			if(place.contains("nj")){
//				url = http + httpRequest.getContextPath();
//			}
//			if(place.contains("cz")){
//				url = http + "/cz";
//			}
//			if(place.contains("tz")){
//				url = http + "/tz";
//			}
//			if(place.contains("nt")){
//				url = http + "/nt";
//			}
//			if(place.contains("ha")){
//				url = http + "/ha";
//			}
//		}else{
//			return null;
//		}
		
		url = url + httpRequest.getServletPath();
		url = url + "_forward";
		if (httpRequest.getQueryString() != null || !"".equals(httpRequest.getQueryString())) {
			url = url + "?" + httpRequest.getQueryString();
		}
		
//		java.util.Enumeration names = httpRequest.getParameterNames();
//		int i = 0;
//		if (names != null) {
//			while (names.hasMoreElements()) {
//				String name = (String) names.nextElement();
//				if (i == 0) {
//					url = url + "?";
//				} else {
//					url = url + "&";
//				}
//				i++; 
//				String value = httpRequest.getParameter(name);
//				if (value == null) {
//					value = "";
//				}
//
//				url = url + name + "=" + value;
//			}
//		} 
		response.setContentType("appliction/json");
		response.setCharacterEncoding("utf-8");
		response.addHeader("Access-Control-Allow-Origin", "*");
//		String responseStr = "";
		//System.out.println(url);
		MiscUtils.getLogger().info(url);
		try {
			URL connection = new URL(url);
			HttpURLConnection urlConnection = (HttpURLConnection)connection.openConnection();
			urlConnection.setDoOutput(true); 
			urlConnection.setDoInput(true);
			urlConnection.setUseCaches(false);
			urlConnection.setRequestProperty("Content-type", "application/x-java-serialized-object");
			
			//GET Request Define:   
//	        urlConnection.setRequestMethod("GET");  
			urlConnection.setRequestMethod("POST");
	        urlConnection.setConnectTimeout(8000);
	        urlConnection.setReadTimeout(8000);
			urlConnection.connect();  
			  
			//Connection Response From Test Servlet  
			MiscUtils.getLogger().info("Connection Response From Test Servlet");  
			InputStream in = urlConnection.getInputStream();  
			
//			InputStream inputStream = urlConnection.getInputStream();
			  
			//Convert Stream to String  
//			responseStr = ConvertToString(inputStream);
			try {		
				//PrintWriter out = response.getWriter();
				ServletOutputStream out = response.getOutputStream();
				int len = 0;
				StringBuilder bulider = new StringBuilder();
				byte[] tmpByte = new byte[1024];
				while ((len = in.read(tmpByte)) != -1) {
					bulider.append(new String(tmpByte, 0, len));
					out.write(tmpByte, 0, len);
				}
				MiscUtils.getLogger().info(bulider.toString());
				//out.print(responseStr);
				out.flush();
				out.close();
			} catch (Exception e) {
				MiscUtils.getLogger().info(e.toString());
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		
//		try {		
//			PrintWriter out = response.getWriter();
//			out.print(responseStr.toString());
//			out.flush();
//			out.close();
//		} catch (Exception e) {
//			MiscUtils.getLogger().info(e.toString());
//		}
		
		return null;
	}
}
